#include "networkconfig.h"

#include <QProcess>

QString OfflineNetworkConfig::address()
{
    return "127.0.0.1";
}

int OfflineNetworkConfig::port()
{
    return 3530;
}

void OfflineNetworkConfig::setup()
{
    emit done();
}

UPNPNetworkConfig::UPNPNetworkConfig()
{   }

void UPNPNetworkConfig::setup()
{
    process = new QProcess();
    connect(process, SIGNAL(finished(int)), this, SLOT(listFinished()));
    process->start("./upnpc-static", QStringList() << "-l");
}

static bool usedPortsContains(QStringList& usedPorts, int port)
{
    foreach(QString sPort, usedPorts)
        if(sPort.toInt() == port)
            return true;
    return false;
}

void UPNPNetworkConfig::listFinished()
{
    QStringList config = QString(process->readAll()).split("\n");

    QStringList usedPorts;

    foreach(QString line, config)
    {
        if(line.startsWith("Local LAN ip address :"))
            localAddress = line.split(":").at(1).trimmed();
        else if(line.startsWith("ExternalIPAddress = "))
            externalAddress = line.split("=").at(1).trimmed();
        else if(line.contains("->"))
            usedPorts << line.split(" ").at(4).split("->").at(0);
    }

    int port = 3530;
    while(usedPortsContains(usedPorts, port))
        port++;

    _port = port;

    delete process;
    process = new QProcess();
    connect(process, SIGNAL(finished(int)), this, SIGNAL(done()));
    process->start("./upnpc-static", QStringList() << "-a" << localAddress << QString().setNum(port) << QString().setNum(port) << "tcp");
}

int UPNPNetworkConfig::port()
{
    return _port;
}

QString UPNPNetworkConfig::address()
{
    return externalAddress;
}
